package cn.gyx.hrm.exception;

import cn.gyx.hrm.constants.ErrorCode;
import cn.gyx.hrm.util.AjaxResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;

/**
 * 全局异常处理
 */
@RestControllerAdvice
public class AllExceptionMine {
    @ExceptionHandler(GlobalException.class)   //处理异常
    public AjaxResult globalExceptionHandler(GlobalException e){
        e.printStackTrace();
        return AjaxResult.me().setSuccess(false).setMessage(e.getMessage());
    }
    //参数校验异常
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public AjaxResult methodArgumentNotValidException(MethodArgumentNotValidException e){
        e.printStackTrace();
        //拿到错误
        List<ObjectError> allErrors = e.getBindingResult().getAllErrors();
        StringBuilder sb = new StringBuilder();
        allErrors.forEach(error->{
            //拿到错误信息，拼接
            sb.append(error.getDefaultMessage()).append(" ; ");
        });
        return AjaxResult.me().setSuccess(false).setMessage(sb.toString());
    }

    @ExceptionHandler(Exception.class)   //处理异常
    public AjaxResult exceptionHandler(Exception e){
        e.printStackTrace();
        return AjaxResult.me().setSuccess(false).setMessage(ErrorCode.SYSTEM_INNER_EXCEPTION.getFullMes());
    }
}
